/**
 * require layui(layer、form、upload), kingeditor
 * @param {Object} options
 */


MZForm = function(options){
	return this.init(options);
}


MZForm.fn = MZForm.prototype = {
	id: '',
	frm: null,
	type: 'data_form',				// data_form or config_form
	layui_form: null,
	layui_upload: null,
	types: [{text:'文本', value:'text'}, {text:'隐藏', value:'hidden'}, {text:'数字', value:'number'},
		{text:'下拉', value:'select'}, {text:'多选', value:'checkbox'}, {text:'开关', value:'switch'},
		{text:'单选', value:'radio'}, {text:'文件', value:'file'}, {text:'文本域', value:'textarea'},
		{text:'富文本', value:'richtext'}, {text:'自定义', value:'html'}, {text:'密码', value:'password'}],
	elements: [],
	data: {},
	_events:{
		submit:[]
	}
}


MZForm.fn.init = function(options){
	var that = this;
	that.id = options.id;
	that.frm = document.getElementById(options.id);
	that.elements = options.elements;
	that.options = options;

	that.frm.setAttribute('lay-filter', options.id)

	var form_html = '', inline_html = '';
	for(var i=0; i<that.elements.length; i++){
		var ele = that.elements[i];
		if('function' == typeof that['_create_' + ele.type] && ele.name){

			var hideItem = ele.type == 'hidden' ? 'style="display:none"' : '';

			if(ele.inline){
				inline_html = '';
				for(; i<that.elements.length; i++){
					ele = that.elements[i];
					if(ele.inline){
						inline_html += '<div class="layui-inline">' + that['_create_' + ele.type](ele) + '</div>';
					}else{
						i--;
						break;
					}
				}
				form_html += '<div class="layui-form-item" '+hideItem+' >' + inline_html + '</div>';

			}else{
				var html = that['_create_' + ele.type](ele);
				form_html += '<div class="layui-form-item" '+hideItem+' >' + html + '</div>';
			}


		}else{
			console.warn('参数错误，已忽略元素' + JSON.stringify(ele));
		}
	}

	//加载内容
	that.frm.innerHTML = form_html;

	layui.use(['form', 'upload', 'element'], function(){
	  	that.layui_form = layui.form;
		that.layui_upload = layui.upload;
		that.layui_form.render();
		that._bind_events();

		if(options.data_url){
			layui.$.get( options.data_url, function(res){
				var data = res.content || {};
				that.layui_form.val(that.id, data);
				that.data = data;

				that._init_editors('.richtext', data);

				if(typeof options.data_loaded == 'function'){
					options.data_loaded(data);
				}
			})
		}else {
			that._init_editors('.richtext', {});
		}
	});
	return that;
}


MZForm.fn.refresh = function(){
	var that = this;
	that.frm = options.frm;

	that.render();
	return that;
}

MZForm.fn._init_editors = function(selector, data){
	//初始化富文本编辑器
	var editors = document.querySelectorAll(selector);
	for(var i=0; i<editors.length; i++){
		var editorId = editors[i].id;
		console.log();
		//KindEditor
		if(typeof KE != 'undefined'){
			KE.show({id:editorId});
			KE.html('editor_id', editors[i].value || '');
		}

		//UEditor
		if(typeof UE != 'undefined'){
			UE.getEditor(editorId);
		}
	}
}


MZForm.fn._bind_events = function(){
	var that = this;


	//上传
	var uploads = document.getElementsByClassName('btn_upload');
	if(uploads.length){

		that.layui_upload.render({
		    elem: '.btn_upload', 		//绑定元素
			field: 'file',
		    auto: true, 				//是否自动上传
			multiple: true,
		    before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
		    //	layer.load(); //上传loading
				var item = this.item;
				obj.preview(function(index, file, result){
					var previewDom = item[0].parentElement.parentElement.querySelector('.upload_preview');
					if(previewDom){
						var preview = '' +
							'<div class="file-item" data-index="'+index+'" style=" position: relative; line-height: 25px; margin: 15px 5px;">' +
							'<div>' +
							'	<a href="" class="file-url-'+index+'" target="_blank" >'+file.name+'</a>' +
							'	<span style="margin-left: 20px;">'+Math.ceil(file.size/1024)+'kb</span>' +
							'	<span class="file-remove layui-icon layui-icon-close" style="margin-left: 20px;font-size: 20px;background: #ddd;border-radius: 10px;"></span>' +
							'</div>' +
							'<div class="layui-progress" style="width: 200px;" lay-filter="file-progress-'+index+'" lay-showPercent="true">' +
							'	<div class="layui-progress-bar" lay-percent="0%"></div>\n' +
							'</div>' +
							'</div>';
						previewDom.innerHTML += preview ;

					}
				});

				layui.$(document).on('click', '.upload_preview .file-remove', function () {

					var index = this.parentNode.parentNode.dataset['index'];
					delete item[0]['done'][index];

					var urls = [];
					for(var k in item[0]['done']){
						urls.push(item[0]['done'][k].url);
					}

					var hiddenVal = item[0].parentElement.querySelector('.ipt_upload_value');
					if(hiddenVal){
						hiddenVal.value = urls.join(',');
					}

					layui.$(this).parents('.file-item').eq(0).remove();
				})
			},
			progress: function(n, elem, res, index){
				layui.element.progress('file-progress-' + index,  n + '%');
			},
		    done: function(res, index, upload){
				//上传完毕回调
				if(res.success){
					var item = this.item;

					var linkDom = item[0].parentElement.parentElement.querySelector('.file-url-'+index);
					if(linkDom){
						linkDom.href = res.url;
					}

					if(!item[0]['done']){
						item[0]['done'] = {};
					}
					item[0]['done'][index] = res;

					var urls = [];
					for(var k in item[0]['done']){
						urls.push(item[0]['done'][k].url);
					}

					var hiddenVal = item[0].parentElement.querySelector('.ipt_upload_value');
					if(hiddenVal){
						hiddenVal.value = urls.join(',');
					}
				}

		      	layer.msg("上传成功");
		    },
		    error: function(){
		      	//请求异常回调
		    },
			allDone: function () {
				layer.closeAll('loading');
			}
	  	});


	}


	//提交
	this.layui_form.on('submit(*)', function(data){
	  	console.log(data.field) //当前容器的全部表单字段，名值对形式：{name: value}

	  	var richEditor = that.getById('#editor_id');
		if(richEditor){
			data.field[richEditor.name] = KE.html('editor_id');
		}

		var form_data = data.field;
		//多选转为拼接值(或数组)
		for(var key in form_data){
			if(/^.*\[.*\]$/.test(key)){
				var k = key.substr(0, key.indexOf('['));
				var tmp = key.substring(key.indexOf('[')+1, key.indexOf(']'));
				form_data[k] = form_data[k] ? form_data[k] + ',' + tmp : tmp;
				delete form_data[key];
			}
		}

		Object.assign(that.data, form_data);

		try{
			that._call_event('submit', form_data);

			if(that.options.submit){
				var params = that.options.submit;
				that.submit(params.post_url, params.put_url, that.data, params.success_url)
			}
		}catch (e) {
			console.log(e);
		}

	 	return false; //阻止表单跳转。如果需要表单跳转，去掉这段即可。
	});
}

MZForm.fn.bind = function(type, fun){
	var that = this;
	if(that._events[type]){
		that._events[type].push(fun);
	}
	return that;
}


MZForm.fn._call_event = function(type, params){
	var that = this;
	var evt = that._events[type];
	if(evt){
		for(var i in evt){
			evt[i](params);
		}
	}
	return that;
}



MZForm.fn.getById = function(id){
	return document.getElementById(id);
}


MZForm.fn.submit = function(post_url, put_url, form_data, success_url){
	var url = form_data.id ? post_url : put_url;

	layui.$.ajax({
		url: url,
		type: form_data.id ? "post" : "put",
		contentType: "application/json",
		data: JSON.stringify(form_data),
		dataType: "json",
		async: false,
		processData: false,
		success: function (res) {
			if(res.content){
				layer.msg('提交成功', function () {
					if(success_url){
						location.href = success_url;
					}
				});
			}else{
				layer.msg('提交失败：' + (res.message || ''));
			}
		}
	});
}


/**
 * 用于外部创建
 * @param {Object} ele
 */
MZForm.fn.createElement = function(ele){
	var that  = this;
	if('function' == typeof that['_create_' + ele.type] && ele.name){
		that.frm.innerHTML += that['_create_' + ele.type](ele);
	}
}


MZForm.fn._create_html = function(ele){
    if('function' == typeof ele.render){
        return ele.render();
    }
	return ele.content;
}


MZForm.fn._create_text = function(ele){
	ele.value = ele.value || '';
	ele.verify = ele.verify || '';
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<input type="text" name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" lay-verify="'+ele.verify+'" placeholder="请输入" autocomplete="off" class="layui-input">' +
	    '	</div>' +
	  	'';
	return tmp;
}

MZForm.fn._create_number = function(ele){
	ele.value = ele.value || '';
	ele.verify = ele.verify || '';
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<input type="number" name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" lay-verify="'+ele.verify+'" placeholder="请输入" autocomplete="off" class="layui-input">' +
	    '	</div>' +
	  	'';
	return tmp;
}

MZForm.fn._create_password = function(ele){
	ele.value = ele.value || '';
	ele.verify = ele.verify || '';
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
		'	<label class="layui-form-label">'+ele.title+'</label>' +
		'	<div class="layui-input-'+cls+'">' +
		'  		<input type="password" name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" lay-verify="'+ele.verify+'" placeholder="请输入" autocomplete="off" class="layui-input">' +
		'	</div>' +
		'';
	return tmp;
}

MZForm.fn._create_hidden = function(ele){
	ele.value = ele.value || '';
	ele.verify = ele.verify || '';
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
		'	<label class="layui-form-label">'+ele.title+'</label>' +
		'	<div class="layui-input-'+cls+'">' +
		'  		<input type="hidden" name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" lay-verify="'+ele.verify+'" placeholder="请输入" autocomplete="off" class="layui-input">' +
		'	</div>' +
		'';
	return tmp;
}

/**
 * 下拉单选
 * @param {Object} ele
 */
 MZForm.fn._create_select = function(ele){
	ele.verify = ele.verify || '';
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<select name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" lay-verify="'+ele.verify+'">';
	for(var i in ele.options){
		var opt = ele.options[i];
		var selected = opt.value == ele.value ? 'selected':'';
		tmp += '	<option value="'+opt.value+'" '+selected+'>'+opt.text+'</option>';
	}
	tmp += '	</select>' +
	    '	</div>' +
	  	'';
	return tmp;
}

/**
 * 复选框
 * @param {Object} ele
 */
MZForm.fn._create_checkbox = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">';
	var values = ele.values || [];
	for(var i in ele.options){
		var opt = ele.options[i];
		var checked = values.indexOf(opt.value) >= 0 ? 'checked' : '';
		tmp += '	<input type="checkbox" name="'+ele.name+'['+opt.value+']" title="'+opt.text+'" '+checked+'>';
	}
	tmp += '</div>' +
	  	'';
	return tmp;
}


/**
 * 开关
 * @param {Object} ele
 */
 MZForm.fn._create_switch = function(ele){
	ele.verify = ele.verify || '';
	var cls = ele.inline ? 'inline' : 'block';
	var checked = ele.value?'checked':'';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<input type="checkbox" name="'+ele.name+'" '+checked+' lay-filter="'+ele.name+'" lay-verify="'+ele.verify+'" lay-skin="switch">' +
	    '	</div>' +
	  	'';
	return tmp;
}


/**
 * 单选
 * @param {Object} ele
 */
MZForm.fn._create_radio = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">';
	for(var i in ele.options){
		var opt = ele.options[i];
		var checked = ele.value == opt.value ? 'checked' : '';
		tmp += '	<input type="radio" name="'+ele.name+'" value="'+opt.value+'" title="'+opt.text+'" '+checked+' >';
	}
	tmp += '</div>' +
	  	'';
	return tmp;
}



MZForm.fn._create_textarea = function(ele){
	ele.verify = ele.verify || '';
	ele.value = ele.value || '';
	var cls = ele.inline ? 'inline' : 'block';
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<textarea name="'+ele.name+'" value="'+ele.value+'" lay-filter="'+ele.name+'" lay-verify="'+ele.verify+'" placeholder="请输入"  class="layui-textarea">'+ele.value+'</textarea>' +
	    '	</div>' +
	  	'';
	return tmp;
}


MZForm.fn._create_richtext = function(ele){
	ele.value = ele.value || '';
	var cls = ele.inline ? 'inline' : 'block';
	var editorId = 'editor_' + ele.name;
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '  		<textarea id="'+editorId+'" name="'+ele.name+'" class="richtext"  style="height: 500px;">'+ele.value+'</textarea>' +
	    '	</div>' +
	  	'';
	return tmp;
}


MZForm.fn._create_file = function(ele){
	var cls = ele.inline ? 'inline' : 'block';
	ele.value = ele.value || '';
	ele.accept = ele.accept || 'file';
	ele.url = ele.url || this.options.upload_url;
	ele.multiple = ele.multiple || false;
	var tmp = '' +
	    '	<label class="layui-form-label">'+ele.title+'</label>' +
	    '	<div class="layui-input-'+cls+'">' +
	    '		<div class="upload_preview" style="margin: 20px 0px;"></div>' +
	    '  		<input type="hidden" class="ipt_upload_value" name="'+ele.name+'" value="'+ele.value+'" />' +
	    '		<button type="button" class="layui-btn layui-btn-sm btn_upload" lay-data="{url: \''+ele.url+'/\', accept: \''+ele.accept+'\', multiple: '+ele.multiple+' }" > ' +
		'  			<i class="layui-icon">&#xe67c;</i>上传' +
		'		</button>' +
	    '	</div>' +
	  	'';

	return tmp;
}




MZForm.fn._create_buttons = function(ele){
	var tmp = '' +
	    '	<div class="layui-input-block">' +
	    '  		<button class="layui-btn" lay-submit lay-filter="*">立即提交</button>' +
	    '  		<button class="layui-btn" type="reset">重置</button>' +
	    '	</div>' +
	  	'';

	return tmp;
}


MZForm.fn.render = function(){
    this.layui_form.render();
}

